<template>
  <canvas ref="canvasRef"></canvas>
</template>

<script setup>
import { onMounted, ref } from "vue";
import {
  BoxBufferGeometry,
  Color,
  Mesh,
  MeshBasicMaterial,
  PerspectiveCamera,
  Scene,
  TextureLoader,
  WebGLRenderer,
  LoadingManager,
} from "three";
// 加载图片资源
import imgSrc1 from "../../assets/image/1.png";
import imgSrc2 from "../../assets/image/2.png";
import imgSrc3 from "../../assets/image/3.png";
import imgSrc4 from "../../assets/image/4.png";
import imgSrc5 from "../../assets/image/5.png";
import imgSrc6 from "../../assets/image/6.png";

const imageSrc = [imgSrc1, imgSrc6, imgSrc3, imgSrc4, imgSrc5, imgSrc2];
const canvasRef = ref(null);

onMounted(() => {
  // 渲染器
  const renderer = new WebGLRenderer({ canvas: canvasRef.value });
  // 相机
  const camera = new PerspectiveCamera(10, 2, 0.1, 1000);
  camera.position.set(0, 0, 100);

  // 场景
  const scene = new Scene();
  scene.background = new Color(0xcccccc);
  //创建立方体
  const box = new BoxBufferGeometry(8, 8, 8);

  // 创建纹理加载器
  const loadingManager = new LoadingManager();
  //纹理加载器
  const loader = new TextureLoader(loadingManager);
  //   纹理设置平铺Texture.repeat.set(2,3)水平重复2次，垂直重复3次
  //   纹理设置偏移量Texture.offset.set(0.5,0.5)
  //   纹理设置旋转中心Texture.center.set(0.5,0.5)，设置旋转弧度（角度转弧度）Texture.rotation=MathUtils.degToRad(45)
  //   纹理设置缩小 Texture.magFilter=NearestFilter/LinearFilter 缩小到最接近模式
  //   纹理设置放大 Texture.minFilter=NearestFilter/LinearFilter 缩小到最接近模式
  const materialArr = [];
  imageSrc.forEach((src) => {
    materialArr.push(
      new MeshBasicMaterial({
        map: loader.load(src),
      })
    );
  });
  //   loadingManager.onLoad = () => {
  //     console.log("纹理图片加载完成");
  //   };
  //   loadingManager.onProgress = (url, loaded, total) => {
  //     console.log(
  //       `纹理图片加载中，共${total}张，当前加载第${loaded}张，资源为：${url}`
  //     );
  //   };
  //   loadingManager.onError = () => {
  //     console.log("纹理图片加载失败");
  //   };

  //   const meterial = new MeshBasicMaterial({
  //     map: loader.load(
  //       imgSrc1,
  //       (texture) => {
  //         console.log(texture);
  //       },
  //       (event) => {
  //         console.log(event);
  //       },
  //       (error)=>{
  //         console.log(error);
  //       }
  //     ),
  //   });

  const mesh = new Mesh(box, materialArr);
  scene.add(mesh);
  //抗锯齿
  const canvas = renderer.domElement;
  camera.aspect = canvas.clientWidth / canvas.clientHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(canvas.clientWidth, canvas.clientHeight, false);

  const rotate = () => {
    scene.rotateY(0.01);
    scene.rotateX(0.01);
    renderer.render(scene, camera);
    requestAnimationFrame(rotate);
  };
  rotate();
  renderer.render(scene, camera);
});
</script>

<style>
canvas {
  display: block;
  width: inherit;
  height: inherit;
}
</style>